package so.shanku.essential.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonMapOrListJsonMap2JsonUtil;
import net.tsz.afinal.json.JsonParseHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.ItemOrderAdapter;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.LogUtil;
import so.shanku.essential.utils.StringUtil;
import so.shanku.essential.view.ListViewNoScroll;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/9/9.
 */
public class UserOrderDetailActivity extends BaseUIActivity {
    /**
     * 订单状态
     */
    @ViewInject(id = R.id.tv_order_style)
    private TextView tv_order_style;
    /**
     * 订单编号
     */
    @ViewInject(id = R.id.tv_order_num)
    private TextView tv_order_num;
    /**
     * 创建时间
     */
    @ViewInject(id = R.id.tv_create_time)
    private TextView tv_create_time;
    /**
     * 用户名
     */
    @ViewInject(id = R.id.tv_order_name)
    private TextView tv_order_name;
    /**
     * 用户手机号
     */
    @ViewInject(id = R.id.tv_order_phone)
    private TextView tv_order_phone;
    /**
     * 用户地址
     */
    @ViewInject(id = R.id.tv_order_address)
    private TextView tv_order_address;
    /**
     * 支付方式
     */
    @ViewInject(id = R.id.tv_pay_style)
    private TextView tv_pay_style;
    @ViewInject(id = R.id.pay_style_layout, click = "pay_style_layout_click")
    private LinearLayout pay_style_layout;
    /**
     * 支付创建时间
     */
    @ViewInject(id = R.id.tv_pay_createtime)
    private TextView tv_pay_createtime;
    /**
     * 商品总价
     */
    @ViewInject(id = R.id.tv_all_money)
    private TextView tv_all_money;
    /**
     * 运费
     */
    @ViewInject(id = R.id.tv_yunfei)
    private TextView tv_yunfei;
    /**
     * 优惠券
     */
    @ViewInject(id = R.id.tv_discount_money)
    private TextView tv_discount_money;

    /**
     * 活动优惠
     */
    @ViewInject(id = R.id.s_a_o_tv_fanxian)
    private TextView tv_qian_fanxian;

    /**
     * 应付总额
     */
    @ViewInject(id = R.id.tv_need_topay)
    private TextView tv_need_topay;
    /**
     * 去支付
     */
    @ViewInject(id = R.id.linear_to_pay)
    private LinearLayout linear_to_pay;

    /**
     * 备注信息
     */
    @ViewInject(id = R.id.s_a_o_et_note)
    private TextView s_a_o_et_note;

    /**
     * 查看物流
     */
    @ViewInject(id = R.id.tv_goods_wuliu, click = "tv_seeLogistics_click")
    private TextView tv_goods_wuliu;

    /**
     * 查看详情
     */
    @ViewInject(id = R.id.tv_order_detail)
    private TextView tv_order_detail;


    /**
     * 确认收货
     */
    @ViewInject(id = R.id.tv_goods_receive_confirm, click = "tv_goods_receive_confirm_click")
    private TextView tv_goods_receive_confirm;

    /**
     * 取消订单
     */
    @ViewInject(id = R.id.tv_order_cancel, click = "iv_pay_cancel_click")
    private TextView tv_order_cancel;

    /**
     * 去支付
     */
    @ViewInject(id = R.id.tv_order_pay, click = "goPay_click")
    private TextView tv_order_pay;

    /**
     * 申请退款
     */
    @ViewInject(id = R.id.tv_fund_return, click = "tv_fund_return_click")
    private TextView tv_fund_return;
    /**
     * 申请退货
     */
    @ViewInject(id = R.id.tv_goods_return, click = "tv_goods_return_click")
    private TextView tv_goods_return;

    /**
     *  添加退货信息
     */
    @ViewInject(id = R.id.tv_do_goods_return, click = "tv_do_goods_return_click")
    private TextView tv_do_goods_return;

    /**
     * 退款详情
     */
    @ViewInject(id=R.id.refund_detail_tv, click = "refund_detail_tv_click")
    private TextView refund_detail_tv;

    @ViewInject(id = R.id.listview_order_detail, itemClick = "listview_order_detail_click")
    private ListViewNoScroll listview_order_detail;

    private String orderId;
    private String orderNum;
    private String vendorId;
    private String totlePrice;
    private List<JsonMap<String, Object>> dataList;
    private String payId;//支付id

    private boolean isRequestServerData=true;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_order_detail);
        setCenter_title(R.string.orderdetail);
        //setBtn_menu(R.drawable.back_goods,back_money);
        orderNum = getIntent().getStringExtra(ExtraKeys.Key_Msg1);
        vendorId=getIntent().getStringExtra(ExtraKeys.Key_Msg2);
        getData_OrderDetail();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if(isRequestServerData) {
            getData_OrderDetail();
        }
        isRequestServerData=false;
    }

    /**
     * 确认收货
     *
     * @param view
     */
    public void tv_goods_receive_confirm_click(View view) {
        goodsReceiveConfirm(orderNum, callBack);
    }

    /**
     * 查看物流
     *
     * @param view
     */
    public void tv_seeLogistics_click(View view) {
        seeLogistics(orderNum);
    }

    /**
     * 取消订单
     *
     * @param view
     */
    public void iv_pay_cancel_click(View view) {
        getData_Cancel_Order(orderId, callBack);
    }

    /**
     * 去支付
     *
     * @param view
     */
    public void goPay_click(View view) {
        //showPayChannelPopView();
        //getData_zhifupeisong();
//		Intent intent = new Intent(this, ShoppingZhifuPeisongWayActivity.class);
//		intent.putExtra(ExtraKeys.Key_Msg1, 1);
//		startActivityForResult(intent, request_payType);
        startPay();
    }

    /**
     * 申请退款
     *
     * @param view
     */
    public void tv_fund_return_click(View view) {
       getFundReturn(orderId, callBack);
        //doGoodsReturn(orderNum,vendorId);//test
    }

    /**
     * 退款详情
     * @param view1
     */
    public void refund_detail_tv_click(View view1){
        scanRefundDetail(orderNum);
    }

    /**
     * 申请退货
     * @param view
     */
    public void tv_goods_return_click(View view) {
        getGoodsReturn(orderNum, callBack);
    }

    /**
     * 退货 进入退货的界面
     *
     * @param view
     */
    public void tv_do_goods_return_click(View view) {
        doGoodsReturn(orderNum,vendorId);
    }

    /**
     * 请求支付
     */
    int request_pay = 1;
    int request_payType = 2;

    public void startPay() {
        LogUtil.d(TAG, "startPay");
        toast.showToast(R.string.start_pay);
        JsonMapOrListJsonMap2JsonUtil<String, Object> util = new JsonMapOrListJsonMap2JsonUtil<String, Object>();
        JsonMap<String, Object> orderdata = new JsonMap<String, Object>();
        orderdata.put("orderNum", orderNum);
        orderdata.put("productName", "商品名称");
        orderdata.put("actualPayPrice", totlePrice);
        orderdata.put("payId", payId);
        Intent intent = new Intent(this, CommitOrderActivity.class);
        intent.putExtra(ExtraKeys.Key_Msg1, 2);
        intent.putExtra(ExtraKeys.Key_Msg2, util.map2Json(orderdata));
        startActivityForResult(intent, request_pay);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == request_pay) {
                finish();
            } else if (requestCode == request_payType) {
                // flushpayandsend(JsonParseHelper.getJsonMap(data
                // .getStringExtra(ExtraKeys.Key_Msg1)));
                String zhifu = data.getStringExtra(ExtraKeys.Key_Msg1);
                payId = data.getStringExtra(ExtraKeys.Key_Msg2);

                tv_pay_style.setText(zhifu);
            }
        }
    }

    /**
     * 商品详情
     */
    public void listview_order_detail_click(AdapterView<?> parent, View view,
                                            int position, long id) {
       String productId= dataList.get(position).getStringNoNull("ProductId");
        seeProductDetail(productId);
    }

    /**
     * 支付方式
     *
     * @param view
     */
    public void pay_style_layout_click(View view) {
        isRequestServerData=false;
        Intent intent = new Intent(this, PayMethodActivity.class);
        intent.putExtra(ExtraKeys.Key_Msg1, 1);
        intent.putExtra(ExtraKeys.Key_Msg2,orderNum);
        startActivityForResult(intent, request_payType);
    }



    /**
     * 订单详情接口
     */
    private void getData_OrderDetail() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orderNum", orderNum);
        GetDataQueue queue = new GetDataQueue();
        queue.setCallBack(callBack);
        queue.setActionName(GetDataConfing.GetAction_GetOrderByOrderNum);
        queue.setWhat(GetDataConfing.what_GetOrderByOrderNum);
        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }

    /**
     * 获取服务器数据的返回信息
     */
    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isOkAndCodeIsNot1(mContext,
                        entity.getInfo())) {
                    if (entity.what == GetDataConfing.what_GetOrderByOrderNum) {
                        List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
                                entity.getInfo(), JsonKeys.Key_Info);
                        setOrderDetail(data);

                    } else if (entity.what == GetDataConfing.what_UpdateOrdersbyOrderNum) {
                        toast.showToast(R.string.shopping_order_option_success);
                        mContext.finish();
                    } else if (entity.what == GetDataConfing.What_ReturnFundByOrderNum) {
                        toast.showToast(R.string.shopping_order_option_success);
                        mContext.finish();
                    } else if (entity.what == GetDataConfing.What_ConfirmOrdersByOrderNum) {
                        toast.showToast(R.string.shopping_order_option_success);
                        mContext.finish();
                    }
                }
            } else {
                ShowGetDataError.showNetError(mContext);
            }
            loadingToast.dismiss();
        }
    };

    /**
     * 订单详情页数据设置
     *
     * @param data
     */
    public void setOrderDetail(List<JsonMap<String, Object>> data) {
        JsonMap jsonMap = data.get(0);
        payId = jsonMap.getStringNoNull("PayTypeId");
        dataList = jsonMap.getList_JsonMap("OrderDetailVOList");
        orderId=jsonMap.getStringNoNull("OrderId");
        vendorId=jsonMap.getStringNoNull("VendorId");
        tv_order_style.setText(jsonMap.getStringNoNull("OrderStatus")); //订单状态
        tv_order_num.setText(jsonMap.getStringNoNull("OrderNum"));  //订单编号
        tv_create_time.setText(jsonMap.getStringNoNull("CreateTime"));   //创建时间
        tv_order_name.setText(jsonMap.getStringNoNull("Consignee"));  //用户名
        tv_order_phone.setText(jsonMap.getStringNoNull("Tel"));    //用户手机号
        tv_order_address.setText(jsonMap.getStringNoNull("Address")); //用户地址
        tv_pay_style.setText(jsonMap.getStringNoNull("PayTypeStr"));  //支付方式
        tv_pay_createtime.setText(jsonMap.getStringNoNull("PayStatus"));//支付状态
        String msg=jsonMap.getStringNoNull("Remark");
        if(!TextUtils.isEmpty(msg)) {
            s_a_o_et_note.setText(msg);
        }
        tv_all_money.setText(StringUtil.getFormatMoneyWithSignMust(jsonMap.getStringNoNull("ProTotalMoney")));//商品总价
        tv_yunfei.setText(StringUtil.getFormatMoneyWithSignMust(jsonMap.getStringNoNull("Freight"))); //运费
        tv_discount_money.setText(StringUtil.getFormatMoneyWithSignMust(jsonMap.getStringNoNull("CouponDiscount"))); //优惠券
        tv_qian_fanxian.setText(StringUtil.getFormatMoneyWithSignMust(jsonMap.getStringNoNull("OrderTypeDiscount", "0")));
        totlePrice = jsonMap.getStringNoNull("RealTotal");
        tv_need_topay.setText(StringUtil.getFormatMoneyWithSignMust(totlePrice)); //应付总额
        JsonMap optionButtonMap = jsonMap.getJsonMap("ShowOrderButton");

        tv_order_cancel.setVisibility(optionButtonMap.getBoolean("IsCancel", false) ? View.VISIBLE : View.GONE);
        tv_order_pay.setVisibility(optionButtonMap.getBoolean("IsPay", false) ? View.VISIBLE : View.GONE);
       // tv_order_detail.setVisibility(optionButtonMap.getBoolean("IsDetail", false) ? View.VISIBLE : View.GONE);
        tv_fund_return.setVisibility(optionButtonMap.getBoolean("IsRefundMoney", false) ? View.VISIBLE : View.GONE);
        tv_goods_wuliu.setVisibility(optionButtonMap.getBoolean("IsSeeLogistics", false) ? View.VISIBLE : View.GONE);
        tv_goods_receive_confirm.setVisibility(optionButtonMap.getBoolean("IsCinfirmReceipt", false) ? View.VISIBLE : View.GONE);
        tv_goods_return.setVisibility(optionButtonMap.getBoolean("IsSalesReturn", false) ? View.VISIBLE : View.GONE);
        // tv_do_goods_return.setVisibility(optionButtonMap.getBoolean("IsReturnGoods",false)? View.VISIBLE : View.GONE);
        refund_detail_tv.setVisibility(optionButtonMap.getBoolean("IsArefundDetails", false) ? View.VISIBLE : View.GONE);

        listview_order_detail.setAdapter(new ItemOrderAdapter(this, dataList));
        pay_style_layout.setClickable(optionButtonMap.getBoolean("IsPay", false) );
    }

}
